/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import model.Artist;
import model.DBManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Album;

/**
 *
 * @author david
 */


public class ArtistFrame extends javax.swing.JFrame {

    /**
     * Creates new form ArtistFrame
     */
    private MenuJFrame parent;
    
    public ArtistFrame() {
        
        em = DBManager.em;
        
        if(!em.getTransaction().isActive())
        {
            em.getTransaction().begin();
        }
        initComponents();
    }
    
    public ArtistFrame(MenuJFrame parent) {
        
        this.parent = parent;
        em = DBManager.em;
        if(!em.getTransaction().isActive())
        {
            em.getTransaction().begin();
        }
        
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        artistQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("Select a from Artist a");
        artistQueryList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(artistQuery.getResultList());
        albumQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("Select a from Album a");
        albumQueryList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(albumQuery.getResultList());
        headerPanel = new javax.swing.JPanel();
        headerLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        artistTable = new javax.swing.JTable();
        exitButton = new javax.swing.JButton();
        actionPanel = new javax.swing.JPanel();
        insertButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        alterButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Αρχείο Καλλιτεχνών");

        headerPanel.setBackground(new java.awt.Color(255, 204, 0));
        headerPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        headerPanel.setToolTipText("null");

        headerLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        headerLabel.setText("Αρχείο Καλλιτεχνών");
        headerLabel.setToolTipText("null");

        javax.swing.GroupLayout headerPanelLayout = new javax.swing.GroupLayout(headerPanel);
        headerPanel.setLayout(headerPanelLayout);
        headerPanelLayout.setHorizontalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headerPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(277, 277, 277))
        );
        headerPanelLayout.setVerticalGroup(
            headerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headerPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(headerLabel)
                .addContainerGap())
        );

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistQueryList, artistTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistLname}"));
        columnBinding.setColumnName("Επώνυμο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistFname}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistArtname}"));
        columnBinding.setColumnName("Καλλιτεχνικό Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistSex}"));
        columnBinding.setColumnName("Φύλο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistBirthDay}"));
        columnBinding.setColumnName("Ημερομηνία Γέννησης");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistBirthPlace}"));
        columnBinding.setColumnName("Τόπος Γέννησης");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicGenreId.musicGenreName}"));
        columnBinding.setColumnName("Είδος Μουσικής");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(artistTable);

        exitButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        exitButton.setText("Επιστροφή στο Μενού");
        exitButton.setToolTipText("null");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        actionPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Επιλογή Ενέργειας"));
        actionPanel.setToolTipText("null");

        insertButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        insertButton.setText("Εισαγωγή");
        insertButton.setToolTipText("null");
        insertButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertButtonActionPerformed(evt);
            }
        });

        deleteButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        deleteButton.setText("Διαγραφή");
        deleteButton.setToolTipText("null");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        alterButton.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        alterButton.setText("Μεταβολή");
        alterButton.setToolTipText("null");
        alterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alterButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout actionPanelLayout = new javax.swing.GroupLayout(actionPanel);
        actionPanel.setLayout(actionPanelLayout);
        actionPanelLayout.setHorizontalGroup(
            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(actionPanelLayout.createSequentialGroup()
                .addComponent(insertButton, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(alterButton, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 13, Short.MAX_VALUE))
        );
        actionPanelLayout.setVerticalGroup(
            actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(actionPanelLayout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addGroup(actionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(insertButton)
                    .addComponent(deleteButton)
                    .addComponent(alterButton)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(headerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 139, Short.MAX_VALUE)
                        .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(headerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(actionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(exitButton)
                        .addGap(9, 9, 9)))
                .addGap(22, 22, 22))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        // TODO add your handling code here:
        parent.setEnabled(true);
        dispose();
    }//GEN-LAST:event_exitButtonActionPerformed

    private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertButtonActionPerformed
        // TODO add your handling code here:
        artist = new Artist();
        em.persist(artist);
        
        EditArtistJFrame editartistframe = new EditArtistJFrame(artist,false);
        editartistframe.setVisible(true);
        
        thisFrame = this;
        thisFrame.setEnabled(false);
        editartistframe.addWindowListener(new WindowListener(){
            
            public void windowClosed(WindowEvent arg0)
            {
                
                System.out.println("Window closed.");
                if(MyWindowEvent.isExitAndSave(arg0))
                {
                    
                    em.getTransaction().commit();
                    em.getTransaction().begin();
                    artistQueryList.add(artist);
                    int row =artistQueryList.size()-1;
                    artistTable.setRowSelectionInterval(row, row);
                    artistTable.scrollRectToVisible(artistTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else
                {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = artistQuery.getResultList();
                    for (Object entity : data)
                    {
                        em.refresh(entity);
                        
                    }
                    artistQueryList.clear();
                    artistQueryList.addAll(data);
                }
                
            }
            
            public void windowActivated(WindowEvent arg0)
            {
                
                System.out.println("Window activated.");
            }
            
            public void windowClosing(WindowEvent arg0)
            {
                
                System.out.println("Window closing.");
            }
            
            public void windowDeactivated(WindowEvent arg0)
            {
                
                System.out.println("Window deactivated.");
            }
            
            public void windowDeiconified(WindowEvent arg0)
            {
                
                System.out.println("Window deiconified.");
            }
            
            public void windowIconified(WindowEvent arg0)
            {
                
                System.out.println("Window iconified.");
            }
            
            public void windowOpened(WindowEvent arg0)
            {
                
                System.out.println("Window opened.");
            }
        });
    }//GEN-LAST:event_insertButtonActionPerformed

    private void alterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterButtonActionPerformed
        // TODO add your handling code here:
        s = artistTable.getSelectedRow();
        if(s<0)
        {
            JOptionPane.showMessageDialog(new JFrame(),"Επέλεξε έναν καλλιτέχνη από τον πίνακα.");
            return;
        }
        artist = artistQueryList.get(s);
        
        EditArtistJFrame eaf = new EditArtistJFrame(artist,true);
        eaf.setVisible(true);
        
        thisFrame = this;
        thisFrame.setEnabled(false);
        eaf.addWindowListener(new WindowListener(){
            
            public void windowClosed(WindowEvent arg0)
            {
                
                System.out.println("Window closed.");
                if(MyWindowEvent.isExitAndSave(arg0))
                {
                    
                    em.merge(artist);
                    em.getTransaction().commit();
                    em.getTransaction().begin();
                    artistQueryList.set(s,artist);
                    artistTable.setRowSelectionInterval(s, s);
                    artistTable.scrollRectToVisible(artistTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                    
                }
                else
                {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = artistQuery.getResultList();
                    for (Object entity : data)
                    {
                        em.refresh(entity);
                        
                    }
                    artistQueryList.clear();
                    artistQueryList.addAll(data);
                }
                
            }
            
            public void windowActivated(WindowEvent arg0)
            {
                
                System.out.println("Window activated.");
            }
            
            public void windowClosing(WindowEvent arg0)
            {
                
                System.out.println("Window closing.");
            }
            
            public void windowDeactivated(WindowEvent arg0)
            {
                
                System.out.println("Window deactivated.");
            }
            
            public void windowDeiconified(WindowEvent arg0)
            {
                
                System.out.println("Window deiconified.");
            }
            
            public void windowIconified(WindowEvent arg0)
            {
                
                System.out.println("Window iconified.");
            }
            
            public void windowOpened(WindowEvent arg0)
            {
                
                System.out.println("Window opened.");
            }
        });
        
    }//GEN-LAST:event_alterButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // TODO add your handling code here:
        s=artistTable.getSelectedRow();
        if (s>=0)
        {
            artist = artistQueryList.get(artistTable.convertRowIndexToModel(s));
            
            try{
                if (artist.getArtistMusicGroupId()!=null)
                {
                    JOptionPane.showMessageDialog(new JFrame(), "Ο επιλεγμένος καλλιτέχνης ανήκει σε συγκρότημα, δεν δύναται να διαγραφεί.");
                    return;
                }
            }catch(Exception e){
                
            }
            
            
            for(Album alb:albumQueryList)
                    {
                        try{
                        if (alb.getArtistId().equals(artist))
                        {
                            JOptionPane.showMessageDialog(new JFrame(), "Ο επιλεγμένος καλλιτέχνης διαθέτει κατχωρημένο άλμπουμ, δεν δύναται να διαγραφεί.");
                            return;
                        }
                        }catch(Exception e){}
                        
                    }
            
            artistQueryList.remove(artist);
            em.remove(artist);
            em.getTransaction().commit();
            em.getTransaction().begin();
        }
        else
        {
            JOptionPane.showMessageDialog(new JFrame(), "Επέλεξε από τον πίνακα έναν καλλιτέχνη για διαγραφή");
            return;
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ArtistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ArtistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ArtistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ArtistFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ArtistFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel actionPanel;
    private javax.persistence.Query albumQuery;
    private java.util.List<Album> albumQueryList;
    private javax.swing.JButton alterButton;
    private javax.persistence.Query artistQuery;
    private java.util.List<Artist> artistQueryList;
    private javax.swing.JTable artistTable;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel headerLabel;
    private javax.swing.JPanel headerPanel;
    private javax.swing.JButton insertButton;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    Artist artist;
    EntityManager em;
    JFrame thisFrame;
    int s;


}
